package test02;

import com.njwb.day16.dom.util.DomUtil;
import org.w3c.dom.Document;
import org.xml.sax.SAXException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.*;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;

public class XmlUtils {

    //获取需要读取的xml文件
    public static Document getDocumentInstance(String path){
        Document document = null ;
        DocumentBuilder documentBuilder = null ;
        try {
            documentBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
            InputStream is = DomUtil.class.getClassLoader().getResourceAsStream(path);
            document=documentBuilder.parse(is);
        } catch (SAXException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ParserConfigurationException e) {
            e.printStackTrace();
        }
        return document;
    }

    public static Document newDocument() {
        Document document = null;
        try {
            DocumentBuilder documentBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
            document = documentBuilder.newDocument();
        } catch (ParserConfigurationException e) {
            e.printStackTrace();
        }
        return document;
    }

    public static void writeDocIntoFile(Document doc, String path) {
        TransformerFactory tff = TransformerFactory.newInstance();
        try {
            Transformer tf = tff.newTransformer();
            DOMSource domSource = new DOMSource(doc);
            Result result = new StreamResult(new File(path));
            tf.transform(domSource, result);
        } catch (TransformerException e) {
            e.printStackTrace();
        }
    }
}
